const express = require('express');
import  React  from 'react';
import { renderToString } from 'react-dom/server';
import { serve,  build,transformSync } from "esbuild";
import { Route ,Routes} from 'react-router-dom';
import { StaticRouter} from 'react-router-dom/server';
const app = express();

app.use(express.static(__dirname + '/public'));
app.get('*',function(req,res){
    build({
		// entryPoints: [path.resolve(__dirname,"../src/App.jsx")],
		entryPoints: ["App.jsx","components/ComA.jsx","components/NotFound.jsx"],
        outdir: './dist',
		minify: false,
		bundle: false,
        write: false,
        format: 'cjs',
        absWorkingDir: '/Users/junyitan/Desktop/study/ssrTemp/my-ssr/client/src/'
	}).then(source => {
		// 获取APP
        const {text} = source.outputFiles.find(item => item.path.indexOf('App.js')>=0); // 获取转换后的文本
        const App = eval(text).default // 文本转runtime 执行
        // 获取ComA
        const {text :comaStr} = source.outputFiles.find(item => item.path.indexOf('ComA.js')>=0); // 获取转换后的文本
        const ComA = eval(comaStr).default // 文本转runtime 执行
        // 获取NotFound
        const {text :noFound} = source.outputFiles.find(item => item.path.indexOf('NotFound.js')>=0); // 获取转换后的文本
        const NotFound = eval(noFound).default // 文本转runtime 执行
        // 生成React元素
        // const MainDom = React.createElement(Main, null);
        // react元素转换成dom字符串
        const content = renderToString( <StaticRouter location={req.url} context={{}}>
            <Routes>
                <Route path="/" element={<App />}></Route>
                <Route path="/coma" element={<ComA />}></Route>
                <Route path="*" element={<NotFound />}></Route>
            </Routes>
        </StaticRouter> );
        const html = `
                <html>
                    <head>
                        <title>MY SSR</title>
                        <link rel="stylesheet" href="App.css">
                        <style>*{margin:0;padding:0}</style>
                    </head>
                    <body>
                        <div id="root">${content}</div>
                        <script>
                            window.__SSR_DATAS = {name: 'Caroline', age: 18}
                        </script>
                        <script type="module" crossorigin src="http://127.0.0.1:8080/assets/index.7c62c197.js"></script>
                        <link rel="modulepreload" href="http://127.0.0.1:8080/assets/vendor.3dd8a18d.js">
                    </body>
                </html>
            `
        res.send(html)
	})
})

app.listen(4000,()=>{
	console.log("服务在4000端口启动")
})